package com.flame.workflow.ru.service;

import java.io.File;
import java.util.List;

import com.flame.auth.core.context.AuthContextHolder;
import com.flame.core.utils.DateUtils;
import com.flame.core.utils.FileUtils;
import com.flame.workflow.exception.WorkflowExcetionMessage;
import com.flame.workflow.exception.WorkflowRuntimeException;
import com.flame.workflow.ru.entity.InstanceFile;
import com.flame.workflow.ru.mapper.InstanceFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 *
 * @author wuxintong😺😺😺
 * @since 2023/11/7
 */
@Service
public class InstanceFileService {

    @Autowired
    private InstanceFileMapper instanceFileMapper;

    @Autowired
    private FileStorageService fileStorageService;

    public void saveFile(Long instanceId, MultipartFile file) {
        String fileId = fileStorageService.saveFile(file);

        InstanceFile dbInstanceFile = instanceFileMapper.findById(fileId);
        if (!ObjectUtils.isEmpty(dbInstanceFile)) {
            throw new WorkflowRuntimeException(WorkflowExcetionMessage.FILE_EXIST);
        }

        InstanceFile instanceFile = new InstanceFile();
        instanceFile.setFileId(fileId);
        instanceFile.setInstanceId(instanceId);
        instanceFile.setUserId(AuthContextHolder.getContext().getAccount());
        instanceFile.setFileName(FileUtils.getFileName(file.getOriginalFilename()));
        instanceFile.setFileSize(String.valueOf(file.getSize()));
        instanceFile.setFileType(FileUtils.getFileType(file.getOriginalFilename()));
        instanceFile.setCreateTime(DateUtils.currentDateTime());
        instanceFileMapper.insert(instanceFile);
    }

    public File getFile(String fileId) {
        return fileStorageService.getFile(fileId);
    }

    public InstanceFile getFileInfo(String fileId) {
        InstanceFile dbInstanceFile = instanceFileMapper.findById(fileId);
        if (ObjectUtils.isEmpty(dbInstanceFile)) {
            throw new WorkflowRuntimeException(WorkflowExcetionMessage.FILE_NOT_EXIST);
        }
        return dbInstanceFile;
    }

    public List<InstanceFile> listInstanceFiles(InstanceFile instanceFile) {
        return instanceFileMapper.listByInstanceId(instanceFile.getInstanceId());
    }
}
